package com.ruoyi.web.controller.self;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.self.domain.RmCourse;
import com.ruoyi.self.domain.RmCourserecord;
import com.ruoyi.self.service.IRmCourseService;
import com.ruoyi.self.service.IRmCourserecordService;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 课程信息Controller
 * 
 * @author ruoyi
 * @date 2019-11-24
 */
@Controller
@RequestMapping("/self/course")
public class RmCourseController extends BaseController
{
    private String prefix = "self/course";

    @Autowired
    private IRmCourseService rmCourseService;

    @Autowired
    private IRmCourserecordService rmCourserecordService;

    @Autowired
    private ISysRoleService roleService;

    @RequiresPermissions("self:course:view")
    @GetMapping()
    public String course()
    {
        return prefix + "/course";
    }

    /**
     * 查询课程信息列表
     */
    @RequiresPermissions("self:course:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RmCourse rmCourse)
    {
        startPage();
        System.out.println("start select !");
        List<RmCourse> list = rmCourseService.selectRmCourseList(rmCourse);
        System.out.println("end select !");
        return getDataTable(list);
    }

    /**
     * 查询课程信息列表
     */
    /*@RequiresPermissions("self:course:list")*/
    @PostMapping("/list2")
    @ResponseBody
    public List<RmCourse> list2(RmCourse rmCourse)
    {
        List<RmCourse> list = rmCourseService.selectRmCourseList(rmCourse);
        return list;
    }


    /**
     * 导出课程信息列表
     */
    @RequiresPermissions("self:course:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RmCourse rmCourse)
    {
        List<RmCourse> list = rmCourseService.selectRmCourseList(rmCourse);
        ExcelUtil<RmCourse> util = new ExcelUtil<RmCourse>(RmCourse.class);
        return util.exportExcel(list, "course");
    }

    /**
     * 新增课程信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存课程信息
     */
    @RequiresPermissions("self:course:add")
    @Log(title = "课程信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("files") MultipartFile[] files, RmCourse rmCourse)
    {

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        System.out.println("filePath:" + filePath);
        String cType =  rmCourse.getCtype();
        // 上传并返回新文件名称
        try {
            String fileNameImag = FileUploadUtils.upload(filePath, files[0]);
            System.out.println("fileNameImag:" + fileNameImag);
            rmCourse.setCimg(fileNameImag);
            if (cType.equals("1")) {
                String fileNameVideo = FileUploadUtils.upload(filePath, files[1]);
                System.out.println("fileNfileNameVideoame:" + fileNameVideo);
                rmCourse.setCpath(fileNameVideo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return toAjax(rmCourseService.insertRmCourse(rmCourse));
    }

    /**
     * 修改课程信息
     */
    @GetMapping("/edit/{cid}")
    public String edit(@PathVariable("cid") Long cid, ModelMap mmap)
    {
        RmCourse rmCourse = rmCourseService.selectRmCourseById(cid);
        mmap.put("rmCourse", rmCourse);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程信息
     */
    @RequiresPermissions("self:course:edit")
    @Log(title = "课程信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam("files") MultipartFile[] files, RmCourse rmCourse)
    {

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        System.out.println("filePath:" + filePath);
        String cType =  rmCourse.getCtype();


        // 上传并返回新文件名称
        if(files != null) {
            for (MultipartFile file : files) {
                int begin = file.getOriginalFilename().indexOf(".");
                int last = file.getOriginalFilename().length();
                //获得文件后缀名
                String fileNameLast = file.getOriginalFilename().substring(begin, last);
                if(fileNameLast.equals(".jpg") || fileNameLast.equals(".png")) {
                    String fileNameImag = null;
                    try {
                        fileNameImag = FileUploadUtils.upload(filePath, file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("fileNameImag:" + fileNameImag);
                    rmCourse.setCimg(fileNameImag);
                }

                if(fileNameLast.equals(".mp4") && cType.equals("1")) {
                    String fileNameVideo = null;
                    try {
                        fileNameVideo = FileUploadUtils.upload(filePath, file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("fileNameVideo:" + fileNameVideo);
                    rmCourse.setCpath(fileNameVideo);
                }
            }
        }
        return toAjax(rmCourseService.updateRmCourse(rmCourse));
    }

    /**
     * 删除课程信息
     */
    @RequiresPermissions("self:course:remove")
    @Log(title = "课程信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(rmCourseService.deleteRmCourseByIds(ids));
    }

    /**
     * 查询课程详细
     */
    @RequiresPermissions("self:course:list")
    @GetMapping("/detail/{cid}")
    public String detail(@PathVariable("cid") Long cid, ModelMap mmap)
    {
        RmCourse rmCourse = rmCourseService.selectRmCourseById(cid);

        Subject subject = SecurityUtils.getSubject();
        SysUser principal = (SysUser)subject.getPrincipal();
        Long userId = principal.getUserId();
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        System.out.println(roles);
        Long activist = 3L;   //入党积极分支角色ID
        Long probationary = 4L;   //预备党员角色ID
        boolean studentFlage = false;
        for(SysRole role: roles) {
            if (role.isFlag()) {
                if (role.getRoleId().equals(activist) || role.getRoleId().equals(probationary)) {
                    studentFlage = true;
                }
            }
        }


        //用户为学生则插入课程学习记录
        if (studentFlage) {
            //插入记录
            Date date = new Date();
            RmCourserecord rmCourserecord = new RmCourserecord();
            rmCourserecord.setLoginName(principal.getLoginName());
            rmCourserecord.setCourseId(cid);
            List<RmCourserecord> rmCourserecordList = rmCourserecordService.selectRmCourserecordListToday(rmCourserecord);
            if (rmCourserecordList.size() == 0) {
                rmCourserecord.setOprTime(date);
                rmCourserecord.setStudyTime(1);
                rmCourserecordService.insertRmCourserecord(rmCourserecord);
            }
        }

        mmap.put("course", rmCourse);
        String cType = rmCourse.getCtype();
        if (cType.equals("1")) {
            return "self/course/profile/courseinfo";
        } else {
            return "self/course/profile/courseinfotext";
        }
    }

    /**
     * 课程中心
     */
    /*@RequiresPermissions("self:course:list")*/
    @GetMapping("/profile/coursecenter")
    public String coursecenter(ModelMap mmap)
    {
        RmCourse rmCourse = new RmCourse();
        rmCourse.setCstatus("0");
        List<RmCourse> rmCourseList = rmCourseService.selectRmCourseList(rmCourse);
        mmap.put("rmCourseList", rmCourseList);
        return prefix + "/profile/coursecenter";
    }
}
